<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中...">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>盘点单明细</span>
        <el-button 
          v-if="inventoryInfo.status === 'PENDING'"
          type="primary" 
          size="small" 
          style="float: right;"
          @click="handleExecute"
        >执行盘点</el-button>
      </div>
      
      <!-- 基本信息 -->
      <div class="info-section">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>计划日期：</label>
              <span>{{ parseTime(inventoryInfo.plannedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>盘点人：</label>
              <span>{{ inventoryInfo.inventoryUser }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>备件仓库：</label>
              <span>{{ getWarehouseName(inventoryInfo.warehouseCode) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <div class="info-item">
              <label>备注：</label>
              <span>{{ inventoryInfo.remark || '无' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 备件信息 -->
      <div class="info-section" style="margin-top: 30px;">
        <h3>备件信息</h3>
        <el-table :data="partList" border class="responsive-table" :fit="true">
          <el-table-column label="备件编号" align="center" prop="partNo" :min-width="140" show-overflow-tooltip />
          <el-table-column label="备件名称" align="center" prop="partName" :min-width="220" show-overflow-tooltip />
          <el-table-column label="规格型号" align="center" prop="specNo" :min-width="140" show-overflow-tooltip />
          <el-table-column label="备件类型" align="center" prop="partTypeCode" :min-width="120">
            <template slot-scope="scope">
              <span>{{ getPartTypeName(scope.row.partTypeCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="理论在库数" align="center" prop="theoreticalQty" :min-width="120" />
          <el-table-column v-if="inventoryInfo.status === 'COMPLETED'" label="实际在库数" align="center" prop="actualQty" :min-width="120" />
          <el-table-column v-if="inventoryInfo.status === 'COMPLETED'" label="盘盈数量" align="center" prop="surplusQty" :min-width="120">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.surplusQty > 0 ? '#67C23A' : '#909399' }">
                {{ scope.row.surplusQty > 0 ? '+' + scope.row.surplusQty : scope.row.surplusQty }}
              </span>
            </template>
          </el-table-column>
          <el-table-column v-if="inventoryInfo.status === 'COMPLETED'" label="盘亏数量" align="center" prop="lossQty" :min-width="120">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.lossQty > 0 ? '#F56C6C' : '#909399' }">
                {{ scope.row.lossQty > 0 ? '-' + scope.row.lossQty : scope.row.lossQty }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="text-align: right; margin-top: 20px;">
        <el-button @click="$router.back()">返 回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getInventory } from '@/api/inventory/inventory'

export default {
  name: 'InventoryDetail',
  data() {
    return {
      sessionNo: '',
      inventoryInfo: {},
      partList: [],
      warehouseOptions: [],
      loading: true
    }
  },
  async created() {
    this.sessionNo = this.$route.params.sessionNo
    this.loading = true
    try {
      // 先加载字典（仓库、备件类型），再拉取详情，避免映射后跳
      await this.loadWarehouses()
      await this.getDetail()
    } catch (error) {
      console.error('加载盘点详情失败:', error)
      this.$message.error('加载数据失败，请重试')
    } finally {
      this.loading = false
    }
  },
  methods: {
    // 加载仓库列表
    loadWarehouses() {
      if (this.$apiWarehouseLoaded) return Promise.resolve()
      return import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouseDTO || mod.listWarehouse || mod.list
        if (!listFn) return
        return listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
          this.warehouseOptions = res.data || res.rows || []
          this.$apiWarehouseLoaded = true
        })
      }).catch(() => { this.warehouseOptions = [] })
    },
    // 获取详情
    getDetail() {
      return getInventory(this.sessionNo).then(res => {
        this.inventoryInfo = res.data
        // 统一在加载字典之后再设置 partList，避免类型编码后跳
        this.partList = (res.data.partList || []).map(p => ({ ...p }))
      }).catch(error => {
        console.error('获取详情失败:', error)
        this.$message.error('获取盘点详情失败')
      })
    },
    // 执行盘点
    handleExecute() {
      this.$router.push({ path: `/system/inventory-execute/${this.sessionNo}` })
    },
    /** 获取仓库名称 */
    getWarehouseName(code) {
      const warehouse = this.warehouseOptions.find(w => w.warehouseCode === code)
      return warehouse ? warehouse.warehouseName : code
    },
    /** 获取备件类型名称（可扩展为从字典接口加载）*/
    getPartTypeName(code) {
      const map = {
        TOOL: '工具',
        PART: '零件',
        CONSUMABLE: '耗材',
        BEARING: '轴承'
      }
      return map[code] || code
    }
  }
}
</script>

<style scoped>
.info-section {
  margin-bottom: 20px;
}

.info-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  margin-bottom: 10px;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
}

/* 表格自适应：固定布局+省略 + 横向滚动 */
.responsive-table .el-table__header-wrapper table,
.responsive-table .el-table__body-wrapper table {
  table-layout: fixed;
  width: 100%;
}
.responsive-table .el-table__body-wrapper { overflow-x: auto; }
.responsive-table .cell { white-space: nowrap; }
</style>
